//
//  AppDelegate.m
//  ERP
//
//  Created by goldeney on 15/1/6.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "MainAppDelegate.h"
#import "UserLoginNSCoding.h"

#import "ExitLoginService.h"
#import "NSKeyedArchiverUserLogin.h"
#import "UIAlertView+EnumView.h"

#import "UserLoginViewController.h"
#import "MainBodyViewController.h"
#import "FunctionIntroduceViewController.h"

#import "OMCreateOrderViewController.h"
#import "OASendApplyViewController.h"
#import "CompanyCardViewController.h"
#import "MessageCenterViewController.h"

#import "GesturesToUnlockViewController.h"
#import "FingerprintLock.h"

#import <CoreLocation/CoreLocation.h>
#import "JPushHttpService.h"
#import "MessageInfoService.h"

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

NSString *NTESNotificationLogout = @"NTESNotificationLogout";

@interface MainAppDelegate()<CLLocationManagerDelegate>

@property (nonatomic, strong, readonly) UIApplicationShortcutItem *shortcutItem;
@property (nonatomic, strong) CLLocationManager *locationManager;

@end

@implementation MainAppDelegate
@synthesize navigationController = _navigationController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //数据库注册
    [MagicalRecord setupCoreDataStackWithStoreNamed:kRecipesStoreName];
    
    //记录UIAlertView
    [UIAlertView startInstanceMonitor];
    
    //初始化组件和注册设备使用权
    [self jPushInitDidFinishLaunchingWithOptions:launchOptions];
    
    //等待1秒进入首页（或功能介绍页面）
    self.navigationController = [[AbstractNavigationController alloc] init];
    [NSThread sleepForTimeInterval:0.5];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];
    
    //首次显示页面设置
    [self setNavigationControllerShowViewControllerForApplication:application launchingWithOptions:launchOptions];
    return YES;
}

#pragma mark - 首次显示页面设置

- (void)setNavigationControllerShowViewControllerForApplication:(UIApplication *)application launchingWithOptions:(NSDictionary *)launchOptions
{
    if (![[NSUserDefaults standardUserDefaults] boolForKey:FirstInstallLaunched]) {//首次安装处理
        [ExitLoginService removePasswdLock];
        FunctionIntroduceViewController *viewController = [[FunctionIntroduceViewController alloc] init];
        [self.navigationController pushViewController:viewController animated:YES];
        
    } else { //按照正常行为处理
        UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
        ConfigurationCodeing *configuration = [ConfigurationHelper getConfigurationData];
        
        if (userInfo && configuration && [GesturesToUnlockViewController hasPwd]) {
            //手势解锁、指纹解锁验证
            [GesturesToUnlockViewController showGesturesToUnlockPresentView:self.navigationController block:^(GesturesToUnlockViewController *lockVC, NSString *pwd) {
                MainBodyViewController *viewController = [[MainBodyViewController alloc] init];
                [self.navigationController pushViewController:viewController animated:NO];
                //跳转3D Touch指定页面
                if(self.shortcutItem) [self performActionForShortcutItem:self.shortcutItem];
                //关闭解锁页面
                [lockVC dismiss:0];
            }];
            
        } else if (userInfo && configuration && [self.navigationController.viewControllers count] <=0) {
            MainBodyViewController *viewController = [[MainBodyViewController alloc] init];
            [self.navigationController pushViewController:viewController animated:NO];
            
        } else {
            [ExitLoginService clearUserLoginData];
        }
    }
    
}

//跳转3D Touch指定页面
- (void)performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem
{
    if([shortcutItem.type isEqualToString:@"com.holui.ERP.KSXD"]){
        //快速下单
        if (![self.navigationController.topViewController isKindOfClass:[OMCreateOrderViewController class]]) {
            OMCreateOrderViewController *viewController = [[OMCreateOrderViewController alloc] init];
            [self.navigationController pushViewController:viewController animated:NO];
        }
        
    } else if([shortcutItem.type isEqualToString:@"com.holui.ERP.SQ"]){
        //发起申请
        if (![self.navigationController.topViewController isKindOfClass:[OASendApplyViewController class]]) {
            OASendApplyViewController *viewController = [[OASendApplyViewController alloc] init];
            [self.navigationController pushViewController:viewController animated:NO];
        }
        
    } else if([shortcutItem.type isEqualToString:@"com.holui.ERP.YQSY"]){
        //邀请使用
        if (![self.navigationController.topViewController isKindOfClass:[CompanyCardViewController class]]) {
            CompanyCardViewController *viewController = [[CompanyCardViewController alloc] init];
            [self.navigationController pushViewController:viewController animated:NO];
        }
    }
}

#pragma mark
#pragma mark - 3D Touch

- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(nonnull void (^)(BOOL))completionHandler
{
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    ConfigurationCodeing *configuration = [ConfigurationHelper getConfigurationData];
    
    //判断是否启用解锁页面，启用就阻止开启3D Touch页面跳转，待解锁后跳转指定页面
    if(shortcutItem && userInfo && configuration){
        _shortcutItem = shortcutItem;
        if ([GesturesToUnlockViewController hasPwd]) return;
        [self performActionForShortcutItem:shortcutItem];
    }
}

#pragma mark (5)(6)
#pragma mark - System Function

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    //销毁3D Touch点击事件内容
    _shortcutItem = nil;
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    //取消标记和通知
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    
    //获取消息
    [MessageInfoService getMessageInfoSaveToSqlite];
    
    //密码锁验证
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    ConfigurationCodeing *configuration = [ConfigurationHelper getConfigurationData];
    
    //手势、指纹解锁页面
    if (userInfo && configuration && [GesturesToUnlockViewController hasPwd]){
        [GesturesToUnlockViewController showGesturesToUnlockPresentView:self.navigationController block:^(GesturesToUnlockViewController *lockVC, NSString *pwd) {
            //跳转3D Touch指定页面
            if(self.shortcutItem) [self performActionForShortcutItem:self.shortcutItem];
            //关闭解锁页面
            [lockVC dismiss:0];
        }];
    }
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Saves changes in the application's managed object context before the application terminates.
    //更新并关闭数据库
    [MagicalRecord cleanUp];
}

#pragma mark - 回收数据

- (void)dealloc
{
    //销毁3D Touch点击事件内容
    _shortcutItem = nil;
    
    //删除通知功能
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/****************************************** 极光推送 *************************************************/

#pragma mark - 注册 registerAPNs

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // 不管app是在前台运行还是在后台运行，系统收到推送时都会调用该方
    
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    //NSLog(@"本地通知，收到通知:%@", [self logDic:notification.userInfo]);
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark -
#pragma mark 极光推送

- (void)jPushInitDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //监听设置
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    //建立连接
    [defaultCenter addObserver:self selector:@selector(networkDidSetup:)
                          name:@"1" object:nil];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        #ifdef NSFoundationVersionNumber_iOS_9_x_Max
        
        #endif
    } else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        
    } else {
        //categories 必须为nil

    }
    
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    
    //2.1.9版本新增获取registration id block接口。
    
    //极光推送-崩溃日志统计
    
    //获取地理位置
    self.locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.distanceFilter = 1000.0f; //如果设为kCLDistanceFilterNone，则每秒更新一次;
    [_locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据（iOS8定位需要）
    if ([CLLocationManager locationServicesEnabled]) {
        // 开启位置更新需要与服务器进行轮询所以会比较耗电，在不需要时用stopUpdatingLocation方法关闭;
        [_locationManager startUpdatingLocation];
    }
}


#pragma mark -
#pragma mark 极光推送 NSNotificationCenter

//建立连接
- (void)networkDidSetup:(NSNotification *)notification
{
    [JPushHttpService deviceStateRegisterChange];//注册设备RegistrationID
}

#pragma mark - CLLocationManagerDelegate
#pragma mar - 地理位置定位

// 地理位置发生改变时触发
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"纬度:%f",newLocation.coordinate.latitude);
    NSLog(@"经度:%f",newLocation.coordinate.longitude);
    
    //极光推送-地理位置统计
    
    // 停止位置更新
    [manager stopUpdatingLocation];
}

// 定位失误时触发
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"error:%@",error);
    if ([error code]==kCLErrorDenied) {
        NSLog(@"访问被拒绝");
    } else if ([error code]==kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
    }
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge; // 推送消息的角标
    NSString *body = content.body; // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
        //[rootViewController addNotificationCount];
        
    } else {
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    //获取消息
    [MessageInfoService getMessageInfoSaveToSqlite];
    
//    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
    completionHandler(UNNotificationPresentationOptionSound);
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"iOS10 收到远程通知:%@", userInfo);
        //[rootViewController addNotificationCount];
        
    } else {
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    //当APP在后台运行时，当有通知栏消息时，点击它，就会执行下面的方法跳转到相应的页面
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateInactive){
        UserLoginNSCoding *userCoding = [NSKeyedArchiverUserLogin getUserLoginData];
        UIViewController *viewController = [[UIApplication sharedApplication] keyWindow].rootViewController;
        //由于有多个UINavigationController嵌套，需要遍历检查
        if([viewController isKindOfClass:[AbstractNavigationController class]]){
            AbstractNavigationController *navigationController = (AbstractNavigationController*)viewController;
            viewController = navigationController.topViewController;
        }
        
        //通知栏跳转消息页面
        if(userInfo && userCoding && ![viewController isKindOfClass:[MessageCenterViewController class]]){
            MessageCenterViewController *viewController = [[MessageCenterViewController alloc] init];
            [self.navigationController pushViewController:viewController animated:NO];
        }
    }
    
    completionHandler();  // 系统要求执行这个方法
}

#endif

@end
